文章目录
  1. 1. 读取方式
  2. 2. 代码实现

Java 开发中,需要将一些易变的配置参数放置再 XML 配置文件或者 properties 配置文件中。然而 XML 配置文件需要通过 DOM 或 SAX 方式解析,而读取 properties 配置文件就比较容易。

读取方式

1、基于ClassLoder读取配置文件

注意:该方式只能读取类路径下的配置文件,有局限但是如果配置文件在类路径下比较方便。

2、基于 InputStream 读取配置文件

注意:该方式的优点在于可以读取任意路径下的配置文件

代码实现

db.properties

1
2
user=root
pwd=123
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package jdbc.com.szxy.properties;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;

/**
* 读取properties文件测试
* @author Momentonly
*/
public class ProPertiesTest {
public static void main(String[] args) throws Exception {
/**
* 基于ClassLoder读取配置文件
*/
Properties pro1 = new Properties();
//获取资源的输入流,类路径下
InputStream is1 =
ProPertiesTest.class.getClassLoader().getResourceAsStream("db.properties");
//读取输入流
pro1.load(is1);
//
System.out.println(pro1.getProperty("user"));
System.out.println(pro1.getProperty("pwd"));
/**
* 基于 InputStream 读取配置文件
*/
Properties pro2 = new Properties();
//获取资源的输入流,相对路径或者绝对路径
InputStream is2 = new FileInputStream(new File("src/db.properties"));
pro2.load(is2);
System.out.println(pro2.getProperty("user"));
System.out.println(pro2.getProperty("pwd"));
}
}
文章目录
  1. 1. 读取方式
  2. 2. 代码实现